package ServiceProvider;

import java.io.*;
import java.util.TimerTask;

import DataCenter.HostAccessor;

public class QueryHeartBeat extends TimerTask {

	private static final String HOST_DOWN = "Queried server has been down and we are looking for another one...";
	private static final String HOST_NOT_FIND = "No host online can be used.";

	private static final long MAX_DELAY = 15000;
	
	private PrintWriter sendWriter;
	private QuerySender querySender;
	
	private long lastReceivedTime;

	public QueryHeartBeat(QuerySender querySender, PrintWriter sendWriter) {
		this.querySender = querySender;
		this.sendWriter = sendWriter;
		lastReceivedTime = System.currentTimeMillis();
	}

	@Override
	public void run() {
		long nowTime = System.currentTimeMillis();
		
		if (querySender.isSendingSuccessful())
			this.cancel();
		else if (nowTime - lastReceivedTime > MAX_DELAY)
		 {
			// current host is wrong, reconnection another online host
			System.out.println(HOST_DOWN);
			
			HostAccessor hostAcr = HostAccessor.sharedInstance();
			String onlineHost = hostAcr.findTheOnlineHost();
			
			if (onlineHost != null) {
				String ip = hostAcr.getTheIpOfHost(onlineHost);
				String port = hostAcr.getThePortOfHost(onlineHost);
				QuerySender sender = new QuerySender(ip, port);
				sender.sendQueryContent(querySender.getQueryContent());
				sender.start();
			} else
				System.out.println(HOST_NOT_FIND);
			
			querySender.close();
			this.cancel();
		}
		else {
			//heart beat normally resend heart beat test
			sendWriter.println("Feed");
			sendWriter.flush();
		}

	}

	public void setLastReceivedTime(long time) {
		this.lastReceivedTime = time;
	}

}
